def isValid(screen, m, n, x, y, prevC, newC):
    if x < 0 or x >= m or y < 0 or y >= n or screen[x][y] != prevC or screen[x][y] == newC:
        return False
    return True

# FloodFill function
def floodFill(screen, m, n, x, y, prevC, newC):
    queue = []

    # Append the position of starting
    # pixel of the component
    queue.append([x, y])

    # Color the pixel with the new color
    screen[x][y] = newC

    # Define 8 possible directions
    directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1)]

    # While the queue is not empty i.e. the
    # whole component having prevC color
    # is not colored with newC color
    while queue:

        # Dequeue the front node
        currPixel = queue.pop()

        posX = currPixel[0]
        posY = currPixel[1]

        # Check if the adjacent pixels are valid
        for direction in directions:
            newX, newY = posX + direction[0], posY + direction[1]

            if isValid(screen, m, n, newX, newY, prevC, newC):
                # Color with newC if valid and enqueue
                screen[newX][newY] = newC
                queue.append([newX, newY])
